﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Collections.ObjectModel;

namespace Datalayer {
    internal class DBConection {
        private const String XMLFilename = "DBConnectionString.xml";
        internal Collection<ConnectionString> DBConections { get; set; }
        private static DBConection _instance;

        public static DBConection GetInstance() {
            if (_instance == null)
                _instance = new DBConection();

            return _instance;
        }

        public static ConnectionString GetConnectionString(string DataBaseName) {
            foreach (ConnectionString item in ReadXML()) {
                if (item.Name.ToUpper() == DataBaseName.ToUpper()) {
                    return item;
                }
            }

            return null;
        }

        private static Collection<ConnectionString> ReadXML() {
            try {
                string Filename = GetFileExists();

                System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(Collection<ConnectionString>));
                StreamReader file = new StreamReader(Filename);

                Collection<ConnectionString> OutXMl = (Collection<ConnectionString>)reader.Deserialize(file);

                file.Close();

                return OutXMl;
            } catch (Exception) {
                throw;
            }
        }

        private static string GetFileExists() {
            string FilenamePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string Filename = String.Format("{0}\\{1}", Path.GetDirectoryName(FilenamePath), XMLFilename);

            if (!File.Exists(Filename)) {
                if (!Filename.Contains("\\bin")) {
                    Filename = String.Format("{0}\\bin\\{1}", Path.GetDirectoryName(FilenamePath), XMLFilename);

                    if (!File.Exists(Filename)) {
                        throw new Exception("DB ConnectionString file missing at location " + Filename);
                    }
                } else {
                    throw new Exception("DB ConnectionString file missing at location " + Filename);
                }
            }

            return Filename;
        }
    }
}
